package com.etc.dysys.admin.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.etc.dysys.admin.service.VideoService;
import com.etc.dysys.admin.service.impl.VideoServiceImpl;
import com.etc.dysys.entity.Video;
import com.etc.dysys.util.AjaxLogicBean;
import com.etc.dysys.util.CommonMessage;
import com.google.gson.Gson;

/**
 * Servlet implementation class VideoServlet
 */
@WebServlet("/Video.action")
public class VideoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private VideoService videoService = new VideoServiceImpl();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String op ="";
		if(request.getParameter("op")!=null) {
			op=request.getParameter("op");
		}
		if(op.equals("addVideo")) {
			doAddVideo(request,response);
		}else if(op.equals("showVideo")) {
			doShowVideo(request,response);
		}else if(op.equals("deleteVideo")) {
			doDeleteVideo(request,response);
		}
	
		
	}
	
	
	/**
	 * 后台删除视频信息的方法
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doDeleteVideo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("application/json");
		int vId = Integer.parseInt(request.getParameter("vId"));
		boolean flag = videoService.deleteVideo(vId);
		CommonMessage comm= new CommonMessage();
		comm.setMsg(flag?"操作成功":"操作失败");
		Gson gson = new Gson();
		String commStr= gson.toJson(comm);
		PrintWriter out = response.getWriter();
		out.print(commStr);
		out.close();
	}
	
	
	/**
	 * 后台查询所有video的方法
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doShowVideo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("application/json");
		AjaxLogicBean<Video> data=videoService.getAll();
		Gson gson = new Gson();
		String pd = gson.toJson(data);
		PrintWriter out = response.getWriter();
		out.print(pd);
		out.close();
	}
	
	
	
	
	/**
	 * 新增视频功能
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doAddVideo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean flag =false;
		String vTitle="";
		
	
		// 创建一个DiskFileItemFactory工厂对象
				DiskFileItemFactory factory = new DiskFileItemFactory();
				// 得到一个文件上传处理的临时目录
				ServletContext servletContext = this.getServletConfig()
						.getServletContext();
				File repository = (File) servletContext
						.getAttribute("javax.servlet.context.tempdir");
				factory.setRepository(repository);

				// ServletFileUpload 核心对象来做文件的上传操作
				ServletFileUpload upload = new ServletFileUpload(factory);

				// 解析request对象
				try {
					List<FileItem> items = upload.parseRequest(request);

					// List的处理 可以使用foreach 也可以用迭代器
					// Process the uploaded items
					Iterator<FileItem> iter = items.iterator();
					while (iter.hasNext()) {
						// FileItem 一个fileItem理解为一个表单的元素对象
						// 按照之前的表单 两个item 文本框 文件域
						FileItem item = iter.next();

						// isFormField() 如果这个item是表单域（表达实际上就是 非文件上传的部分,非文件域）
						if (item.isFormField()) {

							String name = item.getFieldName();
							String value = item.getString();
							
							
							// 这里要判断 和goodsName匹配 name
							if (name.equals("vTitle")) {
								vTitle = value;
							} 
						} else {
							// 文件域的处理
							String fieldName = item.getFieldName();
							String fileName = item.getName(); // 文件名
							String contentType = item.getContentType();
							boolean isInMemory = item.isInMemory();
							long sizeInBytes = item.getSize(); // 大小

							// path应该如何来赋值？ 这个文件上传之后的实际目录是哪里 ->还要将文件名写完整
							// 分析 实际上应该是 tomcat下的webapps/工程名/某个目录 暂时定为 imgs
							String path = request.getRealPath("/imgs/" + fileName);
							// 构建一个FIle对象出来
							File uploadedFile = new File(path);
							// write写 实际就是文件上传的具体动作
							item.write(uploadedFile);
							flag=true;
							String vSrc ="/imgs/" + fileName;
							
							Video video = new Video(0, vSrc, vTitle);
							boolean flag2=videoService.saveVideo(video);
							CommonMessage comm= new CommonMessage();
							String msg="";
							if(flag&&flag2) {
								//上传成功并且保存成功
								request.getRequestDispatcher("/admin/classroom-list.jsp").forward(request, response);
							}else {
								msg="操作失败";
							}
						
				}
					}

				} catch (FileUploadException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
	}
	
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
